package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {

    @Autowired
    private DishService  dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        // 将dish的基本信息保存到 菜品表
        this.save(dishDto);
        // 获取菜品id
        Long id = dishDto.getId();
        // 获取口味的信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((fla) -> {
            fla.setDishId(id);
            return fla;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 修改菜品
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishDto updateByIdd(Long id) {
        // 获取基本菜品信息
        Dish ds = this.getById(id);
        //   获取dishDao对象
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(ds,dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,ds.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    /**
     * 保存修改
     * @param dishDto
     */
    @Override
    public void upDateSave(DishDto dishDto) {
        // 更新基本信息
      this.updateById(dishDto);
      //更新 口味信息
        LambdaQueryWrapper<DishFlavor> lqw =  new LambdaQueryWrapper<>();
        //移除口味
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
       // 在新口味中添加ID
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map(flavor -> {
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());

        // 保存口味
        dishFlavorService.saveBatch(flavors);
    }
}